import { defineStore } from 'pinia'
import { getCategoryList, type CategoryVO } from '@/api/mall/product/category'
import { getSpuPage, getSpu, type Spu } from '@/api/mall/product/spu'

export const useProductStore = defineStore('product', {
  state: () => ({
    categories: [] as CategoryVO[],
    categoryLoading: false,
    products: [] as Spu[],
    total: 0,
    listLoading: false,
    detail: null as Spu | null
  }),
  actions: {
    async fetchCategories() {
      this.categoryLoading = true
      try {
        this.categories = await getCategoryList({})
      } catch (e: any) {
        console.warn('获取分类失败:', e?.message || e)
        this.categories = []
      } finally {
        this.categoryLoading = false
      }
    },
    async fetchProducts(params: { pageNo?: number; pageSize?: number; name?: string; categoryId?: number }) {
      this.listLoading = true
      try {
        const { list, total } = await getSpuPage({ pageNo: params.pageNo || 1, pageSize: params.pageSize || 12, name: params.name, categoryId: params.categoryId })
        this.products = list
        this.total = total
      } catch (e: any) {
        console.warn('获取商品失败:', e?.message || e)
        this.products = []
        this.total = 0
      } finally {
        this.listLoading = false
      }
    },
    async fetchDetail(id: number) {
      try {
        this.detail = await getSpu(id)
        return this.detail
      } catch (e: any) {
        console.warn('获取商品详情失败:', e?.message || e)
        this.detail = null
        return null as any
      }
    }
  }
})